package com.icss.company.controller;

import com.icss.company.pojo.Emp;
import com.icss.company.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/emp")
public class EmpController {

    @Autowired
    private EmpService empService;

    @PostMapping("/searchEmp")
    public Map<String,Object> searchEmp(String ename, String deptno) {
        Map<String,Object> params = new HashMap<>();
        params.put("ename", ename);
        params.put("deptno", deptno);

        Map<String,Object> result = new HashMap<>();
        try {
            result.put("code","200");
            result.put("msg","查询成功");
            result.put("data",empService.search(params));
        } catch (Exception e) {
            result.put("code","500");
            result.put("msg","查询失败");
        }
        return result;
    }


    @GetMapping("/listEmp")
    public Map<String,Object> listEmp(String ename){
        Map<String,Object> result = new HashMap<>();
        result.put("code","200");
        result.put("msg","查询成功");
        result.put("data",empService.list(ename));
        return result;
    }

    @GetMapping("/delEmp/{empno}")
    public Map<String,Object> delEmp(@PathVariable("empno") Integer empno){
        Map<String,Object> result = new HashMap<>();
        if(empService.del(empno)){
            result.put("code","200");
            result.put("msg","删除成功");
        }else{
            result.put("code","500");
            result.put("msg","删除失败");
        }
        return result;
    }

    @GetMapping("/getEmp/{empno}")
    public Map<String,Object> getEmp(@PathVariable("empno") Integer empno) {
        Map<String,Object> result = new HashMap<>();
        result.put("code","200");
        result.put("msg","操作成功");
        result.put("data",empService.get(empno));
        return result;
    }

    @PostMapping("/addEmp")
    public Map<String,Object> addEmp(@RequestBody Emp emp){  // 添加 @RequestBody
        Map<String,Object> result = new HashMap<>();
        if(empService.add(emp)){
            result.put("code","200");
            result.put("msg","新增成功");
        }else{
            result.put("code","500");
            result.put("msg","新增失败");
        }
        return result;
    }

    @PostMapping("/updateEmp")
    public Map<String,Object> updateEmp(@RequestBody Emp emp){  // 添加 @RequestBody
        Map<String,Object> result = new HashMap<>();
        if(empService.update(emp)){
            result.put("code","200");
            result.put("msg","新增成功");
        }else{
            result.put("code","500");
            result.put("msg","新增失败");
        }
        return result;
    }
}
